package com.javaweb.blogcite.service.Impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.blogcite.common.PageData;
import com.javaweb.blogcite.mapper.MessageMapper;
import com.javaweb.blogcite.pojo.Message;
import com.javaweb.blogcite.service.MessageService;
import com.javaweb.blogcite.util.AvatarUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private MessageMapper messageMapper;

    @Override
    public Message postMessage(Message message) {
        // 从 res 目录中随机选取一个头像
        message.setAvatar(AvatarUtil.getAvatar());
        message.setCreateDate(new Date().getTime());
        int rows = messageMapper.insert(message);

        // 从数据库中获取该条数据
        return messageMapper.selectById(message.getId());
    }

    @Override
    public boolean deleteMessage(Integer id) {
        int rows = messageMapper.deleteById(id);
        return rows > 0;
    }

    @Override
    public PageData<Message> getMessagesByPage(Integer page, Integer limit) {
        IPage<Message> pageHelper = new Page<>(page, limit);
        IPage<Message> messageIPage = messageMapper.selectPage(pageHelper, null);
        long total = messageIPage.getTotal();
        List<Message> messageList = messageIPage.getRecords();
        return new PageData<>(total, messageList);
    }
}
